package cn.hp.beauty.common.security;

import cn.hp.beauty.domain.Menu;
import cn.hp.beauty.domain.Role;
import cn.hp.beauty.domain.Userinfo;
import cn.hp.beauty.service.MenuService;
import cn.hp.beauty.service.RoleService;
import cn.hp.beauty.service.UserinfoService;
import cn.hp.beauty.util.JwtUtil;
import cn.hp.beauty.util.Result;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserinfoService userinfoService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputstream = response.getOutputStream();
        String username = authentication.getName();
        String token = JwtUtil.genJwtToken(username);

        // 将用户信息返回
        Userinfo userinfo = userinfoService.findUserByUsername(username);

        // 菜单返回
        // 第一步：查询用户的角色
        List<Role> roleList = roleService.findRoleByUId(userinfo.getUId());

        userinfo.setRoles(roleList.stream().map(Role::getRName).collect(Collectors.joining(",")));

        // 第二步：遍历用户的角色，根据角色找到资源，并去重
        Set<Menu> menuSet = new HashSet<>();
        for (Role role : roleList) {
            List<Menu> menuList = menuService.findMenuByRId(role.getRId());
            for (Menu menu : menuList) {
                menuSet.add(menu);
            }
        }

        // 将set转换为list,为了排序
        List<Menu> oldMenuList = new ArrayList<>(menuSet);
        // 排序
        oldMenuList.sort(Comparator.comparing(Menu::getMOrderNum));
        // 将list转换为树形结构
        List<Menu> menuList = menuService.buildTreeMenu(oldMenuList);

        Map<String, Object> map = new HashMap<>();
        map.put("userinfo", userinfo);
        map.put("menuList", menuList);

        outputstream.write(JSONUtil.toJsonStr(Result.success(map,token)).getBytes());
        outputstream.flush();
        outputstream.close();
    }
}
